<template>
  <div id="interMethodDiv">
    <Splitpanes>
      <Pane size="50">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" :loading="rloading" :disabled="isEmpty(interId)" @click="findInterfaceMethodList"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" :disabled="isEmpty(interId)" @click="addInterfaceMethod(null)"></vxe-button>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-save" content="保存" :disabled="isEmpty(interId)" @click="saveBathInterfaceMethod"></vxe-button>
            <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" :disabled="isEmpty(interId)" @click="deleteInterfaceMethod"></vxe-button>
          </template>
        </vxe-toolbar>
        <div class="tableBox">
          <vxe-table ref="methodTableRef" class="mytable-scrollbar" border="inner" align="left" height="auto" :row-config="{ isCurrent: true, isHover: true }" :data="methodList" :loading="rloading" @current-change="methodRowClick" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'cell', showStatus: true }" resizable show-overflow keep-source>
            <vxe-column type="checkbox" width="30"></vxe-column>
            <vxe-column field="interfaceGroupName" title="分组类型" width="100"></vxe-column>
            <vxe-column field="orderCode" title="编号" width="50"></vxe-column>
            <vxe-column field="seq" title="seq" width="50" :edit-render="{}">
              <template #edit="{ row }">
                <vxe-input v-model="row.seq" type="number"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="interfaceDictId" title="接口方法" width="100" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ row.interfaceDictName }}</span>
              </template>
              <template #edit="{rowIndex }">
                {{addInterfaceMethod(rowIndex)}}
              </template>
            </vxe-column>

            <vxe-column field="asName" title="方法别名" width="100" :edit-render="{}">
              <template #edit="{ row}">
                <vxe-input v-model="row.asName" placeholder type="text"></vxe-input>
              </template>
            </vxe-column>
            <vxe-column field="isEnable" title="是否启用" width="100" :edit-render="{}">
              <template #default="{ row }">
                <el-tag :type="row.isEnable ? 'success' : 'danger'">{{ row.isEnable ? '是' : '否' }}</el-tag>
              </template>
              <template #edit="{ row }">
                <vxe-switch v-model="row.isEnable" open-label="是" close-label="否"></vxe-switch>
              </template>
            </vxe-column>

            <vxe-column field="execMode" title="执行方式" width="100" :edit-render="{}">
              <template #default="{ row }">
                <span>{{ formatCommon(execModeList, row.execMode) }}</span>
              </template>
              <template #edit="{ row }">
                <vxe-select v-model="row.execMode" transfer>
                  <vxe-option v-for="item in execModeList" :key="item.id" :value="item.code" :label="item.name"></vxe-option>
                </vxe-select>
              </template>
            </vxe-column>
            <vxe-column field="methodData" title="方法配置" width="200" :edit-render="{}">
              <template #edit="{ row, rowIndex }">
                <vxe-input v-model="row.methodData" readonly type="text" @dblclick="methodDataDblclick(row, rowIndex)"></vxe-input>
              </template>
            </vxe-column>

            <vxe-column field="remark" title="备注" width="100" :edit-render="{}">
              <template #edit="{ row}">
                <vxe-input v-model="row.remark" placeholder type="text"></vxe-input>
              </template>
            </vxe-column>
          </vxe-table>
        </div>
      </Pane>
      <Pane size="50">
        <el-tabs type="border-card" v-model="activeName" @tab-click="tabHandleClick">
          <el-tab-pane label="外源设置" name="first" :disabled="isEmpty(sltMethod)">
            <InterfaceMethodExternal v-if="dataType!='WEB'" ref="interMethodExternalRef" @sucCallBack="extParamsSaveSucCallback" />
            <InterfaceMethodExternalWeb v-if="dataType=='WEB'" ref="interMethodExternalWebRef" @sucCallBack="extParamsSaveSucCallback" />
          </el-tab-pane>
          <el-tab-pane label="出参设置" name="second" :disabled="isEmpty(sltMethod)">
            <InterfaceMethodOutParam ref="interMethodOutParamRef" />
          </el-tab-pane>
          <el-tab-pane label="场景选项" name="thrid" :disabled="isEmpty(sltMethod)">
            <InterfaceMethValue ref="interMethValueRef" />
          </el-tab-pane>
          <el-tab-pane label="调试" name="four" :disabled="isEmpty(sltMethod)">
            <CompIntfItemTest ref="CompIntfItemTestRef" />
          </el-tab-pane>
        </el-tabs>
      </Pane>
    </Splitpanes>

    <el-dialog title="方法配置" width="800px" :show-close="false" :draggable="true" v-model="showDialog" :append-to-body="true" :close-on-click-modal="false">
      <el-form ref="reamrkFormRef" :model="reamrkForm" label-width="80px" class="form-input-l" :inline-message="true">
        <el-form-item prop="solution" label="方法配置">
          <el-input :autosize="{ minRows: 10, maxRows: 30 }" v-model="reamrkForm.methodData" type="textarea"></el-input>
        </el-form-item>

        <el-form-item prop="dictRemark" label="说明">
          <el-input type="textarea" :autosize="{ minRows: 10, maxRows: 30 }" disabled v-model="reamrkForm.dictRemark" />
        </el-form-item>
      </el-form>
      <div class="dialog-footer flex justify-end">
        <el-button type="primary" @click="confirmDialog('reamrkFormRef')">确定</el-button>
        <el-button @click="closeDialog('reamrkFormRef')">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="选择`接口" width="700px" :show-close="false" :draggable="true" v-model="addDialog" :append-to-body="true" :close-on-click-modal="false" class="interfacesetDialogAdd">
      <div class="tableBody" style="height: 600px">
        <vxe-toolbar perfect>
          <template #buttons>
            <vxe-input v-model="keyWords" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @keyup="keyupEnter" @clear="findLabItemList()" @search-click="findLabItemList()"></vxe-input>
            <vxe-button type="text" class="button-blue" icon="vxe-icon-refresh" content="刷新" @click="findLabItemList"></vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table ref="labInterfaceTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="labInterfaceList" :loading="lloading" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" @current-change="rptRowClick" resizable show-overflow keep-source>
          <vxe-column field="code" title="接口代码"></vxe-column>
          <vxe-column field="name" title="接口名称"></vxe-column>
          <vxe-column field="orderCode" title="接口编号"></vxe-column>
        </vxe-table>
        <el-form ref="addFormRef" :model="addForm" label-width="80px" class="form-input-m interfaceSetAddForm" :inline-message="true">
          <el-form-item prop="asName" label="接口别名">
            <el-input placeholder="请输入内容" v-model="addForm.asName" />
          </el-form-item>
        </el-form>
      </div>
      <div class="dialog-footer flex justify-end">
        <el-button type="primary" @click="confirmAddDialog()">确定</el-button>
        <el-button @click="closeAddDialog()">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import { Splitpanes, Pane } from 'splitpanes';
import moment from 'moment';
let { proxy }: any = getCurrentInstance();
import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示
import { isEmpty } from 'lodash';
import { IsEmpty } from '@/utils/common';
import { AppStore } from '@/stores/store';
import SelectDataGrid from '@/components/SelectDataGrid.vue';
import InterfaceMethodExternal from './InterfaceMethodExternal.vue';
import InterfaceMethodExternalWeb from './InterfaceMethodExternalWeb.vue';
import InterfaceMethodOutParam from './InterfaceMethodOutParam.vue';
import InterfaceMethValue from './InterfaceMethValue.vue';
import CompIntfItemTest from './compIntfSettings/CompIntfItemTest.vue';

let store = AppStore();
defineExpose({ initPage });
let interId = null;
let dataType = ref(null);
let dataIndex = ref(null);
let methodList: any = reactive([]);
let execModeList: any = reactive([]); //选择字典
let rloading = ref(false);
let lloading = ref(false); //弹框表格数据加载状态
let sltMethod: any = ref({});
let activeName = ref('first');
let keyWords = ref('');
let interMethodExternalRef: any = ref(null);
let interMethodExternalWebRef: any = ref(null);
let interMethodOutParamRef: any = ref(null);
let interMethValueRef: any = ref(null);
const CompIntfItemTestRef: any = ref(null);
let currentRow: any = reactive({});
let labInterfaceList: any = reactive([]); //弹框表格数据


function initPage(row: any) {
  dataType.value = row.interfaceType;
  interId = row.id;
  findInterfaceMethodList();
}

// 页面加载时更新列表(左侧)
onMounted(() => {
  getDictItemsList();
});

// 点击当前行// 行点击事件
function rptRowClick({ row }: any) {
  const $reportTable = proxy.$refs.labInterfaceTableRef;
  if ($reportTable) {
    $reportTable.setCurrentRow(row);
  }
  addForm.interfaceDictId = row.id;
  addForm.asName = row.name;
  addForm.interfaceDictName = row.name;
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findLabItemList();
  }
}


// 获取弹框表格数据
function findLabItemList() {
  lloading.value = true;
  const url = '/api/sys/getInterfaceDictList';
  labInterfaceList.length = 0; //放入数据前清空数据
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        keyWords: keyWords.value
      }
    })
    .then((res: any) => {
      labInterfaceList.push(...res.data);
      if (labInterfaceList.length > 0) {
        rptRowClick({ row: labInterfaceList[0] });
      }
      lloading.value = false;
    })
    .catch((err: any) => {
      lloading.value = false;
      VxeMessage('获取获取弹框表格数据异常', VxeNotifyType.error);
    });
}

// 通用行合并函数（将相同多列数据合并为一行）
/*const mergeRowMethod = ({ row, _rowIndex, column, visibleData }) => {
  const fields = ['interfaceGroupName'];
  const cellValue = row[column.field];
  if (cellValue && fields.includes(column.field)) {
    const prevRow = visibleData[_rowIndex - 1];
    let nextRow = visibleData[_rowIndex + 1];
    if (prevRow && prevRow[column.field] === cellValue) {
      return { rowspan: 0, colspan: 0 };
    } else {
      let countRowspan = 1;
      while (nextRow && nextRow[column.field] === cellValue) {
        nextRow = visibleData[++countRowspan + _rowIndex];
      }
      if (countRowspan > 1) {
        return { rowspan: countRowspan, colspan: 1 };
      }
    }
  }
};*/
//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['execMode'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const execMode = dictTreeTypeItems.data.find((item) => item.code === 'execMode');
  execModeList.push(...execMode.detailDataList);
}

// 获取左侧仪器表格数据+刷新+右侧表格数据
function findInterfaceMethodList() {
  rloading.value = true;
  methodList.length = 0; //放入数据前清空数据
  if (isEmpty(interId)) {
    rloading.value = false;
    return;
  }
  const url = '/api/sys/sysInterfaceMethod/findInterfaceMethodList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: { interfaceId: interId }
    })
    .then((res: any) => {
      if (res.status.code === 1) {
        methodList.push(...res.data.detailList);
        rloading.value = false;
        const kn = methodList.find((k) => k.id == sltMethod.value.id);
        if (isEmpty(kn)) {
          methodRowClick({ row: methodList[0] }); //默认选中第一条数据
        } else {
          methodRowClick({ row: kn }); //默认选中第一条数据
        }
      } else {
        rloading.value = false;
        VxeMessage('获取列表失败', VxeNotifyType.error);
      }
    })
    .catch((err: any) => {
      rloading.value = false;
      VxeMessage('获取表格数据异常', VxeNotifyType.error);
    });
}

function methodRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltMethod.value = {};
  } else {
    (proxy.$refs.methodTableRef as any).setCurrentRow(row);
    sltMethod.value = row;
  }
  Object.assign(currentRow, row);
  if (activeName.value == 'first') {
    if (interMethodExternalRef.value) {
      interMethodExternalRef.value.initPage(currentRow);
    } else {
      interMethodExternalWebRef.value.initPage(currentRow);
    }
  } else if (activeName.value == 'second') {
    interMethodOutParamRef.value.initPage(currentRow);
  } else if (activeName.value == 'thrid') {
    interMethValueRef.value.initPage(sltMethod.value);
  } else if (activeName.value == 'four') {
    CompIntfItemTestRef.value?.initPage(currentRow);
  }
}

function addInterfaceMethod(index) {

  if (isEmpty(interId)) {
    VxeMessage('请维护接口信息', VxeNotifyType.error);
    return;
  }
  if (!IsEmpty(index)) {
    dataIndex.value = index;
  } else {
    dataIndex.value = null;
  }
  addDialog.value = true;
  findLabItemList();
}

async function saveBathInterfaceMethod() {
  if (isEmpty(interId)) {
    VxeMessage('请选择接口', VxeNotifyType.error);
  } else {
    let $Xtable = proxy.$refs.methodTableRef;
    if ($Xtable) {
      // 表格实例表用该方法拿到有id的为修改
      const updateRecords = await $Xtable.getUpdateRecords().filter((p: any) => {
        return p.id && p.id !== '';
      });
      // 拿到数组中没有id的数据为新增
      const InsertRecords = methodList.filter((e: any) => {
        return !e.id || e.id === '';
      });

      const sveOrupdateDetail = [] as any[];
      updateRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          interfaceId: e.interfaceId,
          interfaceDictId: e.interfaceDictId,
          execMode: e.execMode,
          remark: e.remark,
          dictRemark: e.dictRemark,
          methodData: e.methodData,
          isEnable: e.isEnable,
          seq: e.seq,
          orgId: e.orgId,
          asName: e.asName
        };

        sveOrupdateDetail.push(iDetail);
      });
      InsertRecords.forEach((e: any) => {
        const iDetail: any = {
          id: e.id,
          interfaceId: e.interfaceId,
          interfaceDictId: e.interfaceDictId,
          execMode: e.execMode,
          remark: e.remark,
          dictRemark: e.dictRemark,
          methodData: e.methodData,
          isEnable: e.isEnable,
          seq: e.seq,
          orgId: e.orgId,
          asName: e.asName
        };
        sveOrupdateDetail.push(iDetail);
      });

      if (sveOrupdateDetail.length > 0) {
        const url = '/api/sys/sysInterfaceMethod/saveOrUpdateInterfaceMethod';
        const obj: any = {};
        obj.methodList = sveOrupdateDetail;
        proxy.$http
          .post(url, obj)
          .then((res: any) => {
            VxeMessage('更新成功', VxeNotifyType.success);
            findInterfaceMethodList();
          })
          .catch((err: any) => {
            VxeMessage('更新失败', VxeNotifyType.success);
          });
      } else {
        VxeMessage('无添加或修改数据', VxeNotifyType.error);
      }
    } else {
      return;
    }
  }
}

function deleteInterfaceMethod() {
  const sltDetails = (proxy.$refs.methodTableRef as any).getCheckboxRecords();
  if (!(sltDetails.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(async () => {
        //后台删除数据
        const delDetailList = sltDetails.filter((p: any) => !isEmpty(p.id));
        if (delDetailList.length > 0) {
          const data = { methodList: delDetailList };
          const url = '/api/sys/sysInterfaceMethod/deleteBatchInterfaceMethod';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findInterfaceMethodList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        }
        //页面删除未保存的数据
        const removeDetailList = sltDetails.filter((p: any) => isEmpty(p.id));
        if (removeDetailList.length > 0) {
          // 删除的新增的空白数据 不走接口
          let $Xtable = proxy.$refs.methodTableRef;
          if ($Xtable) {
            for (const removeRow of removeDetailList) {
              methodList.splice(removeRow.seq - 1);
            }
          }
        }
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }
}
/**外源参数保存成功回调刷新 */
function extParamsSaveSucCallback() {
  findInterfaceMethodList();
}
let showDialog = ref(false); //添加弹框展示状态
let addDialog = ref(false); //添加弹框展示状态
let reamrkForm = reactive({
  methodData: '',
  dictRemark: '',
  index: 0
});
let addForm = reactive({
  interfaceDictId: '',
  interfaceDictName: '',
  asName: ''
});

function methodDataDblclick(row, index) {
  reamrkForm.index = index;
  reamrkForm.methodData = row.methodData;
  reamrkForm.dictRemark = row.dictRemark;
  showDialog.value = true;
}

function closeDialog(formName: any) {
  const el: any = proxy.$refs[formName];
  //移除校验结果
  el.clearValidate();
  clearReamrkForm();
  showDialog.value = false;
}
function closeAddDialog() {
  clearAddReamrkForm();
  addDialog.value = false;
}

function clearReamrkForm() {
  reamrkForm.index = 0;
  reamrkForm.methodData = '';
  reamrkForm.dictRemark = '';
}

function clearAddReamrkForm() {
  addForm.interfaceDictId = '';
  addForm.asName = '';
}

function confirmDialog() {
  methodList[reamrkForm.index].methodData = reamrkForm.methodData;
  showDialog.value = false;
}
function confirmAddDialog() {
  if (isEmpty(addForm.interfaceDictId) || isEmpty(addForm.asName)) {
    VxeMessage('接口方法和别名不能为空', VxeNotifyType.error);
    return;
  }
  if (!IsEmpty(dataIndex.value)) {
    methodList[dataIndex.value].interfaceDictName = addForm.interfaceDictName;
    methodList[dataIndex.value].interfaceDictId = addForm.interfaceDictId;
    methodList[dataIndex.value].asName = addForm.asName;
  } else {
    const record: any = {
      id: '',
      interfaceId: interId,
      interfaceDictId: addForm.interfaceDictId,
      asName: addForm.asName,
      execMode: '',
      remark: '',
      dictRemark: '',
      methodData: '',
      isEnable: true,
      seq: methodList.length + 1,
      orgId: store.userInfo.orgId
    };
    methodList.push(record);
  }
  saveBathInterfaceMethod();
  addDialog.value = false;

}

function tabHandleClick(tab) {
  if (tab.index == 0) {
    if (interMethodExternalRef.value) {
      interMethodExternalRef.value.initPage(currentRow);
    } else {
      interMethodExternalWebRef.value.initPage(currentRow);
    }
  } else if (tab.index == 1) {
    interMethodOutParamRef.value.initPage(sltMethod.value);
  } else if (tab.index == 2) {
    interMethValueRef.value.initPage(sltMethod.value);
  } else if (tab.index == 3) {
    CompIntfItemTestRef.value.initPage(currentRow);
  }
}

// 获取组件当前行数据
function selectDictRow(row, index) {
  methodList[index].interfaceDictName = row.name;
  methodList[index].interfaceDictId = row.id;
  methodList[index].dictRemark = row.remark;
}

// 获取组件当前行数据
function selectAddDictRow(row, index) {
  addForm.interfaceDictId = row.id;
  addForm.asName = row.name;
}
function formatCommon(arr, value) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
</script>

<style lang="scss" scoped>
#interMethodDiv {
  height: 100%;

  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }

  //左侧表格
  .tableBox {
    height: calc(100% - 40px);
    background-color: $base-white;
  }

  .el-tabs {
    height: 100%;

    :deep(.el-tabs__content) {
      padding: 0;
      height: calc(100% - 39px);

      .el-tab-pane {
        height: 100%;
      }
    }
  }
}
</style>

<style lang="scss">
// 针对新增弹框样式
.interfacesetDialogAdd {
  padding: 0 !important;
  // 附加按钮间距
  .button-blue,
  .button-red {
    margin: 5px 0 5px 5px;
  }
  .interfaceSetAddForm {
    margin: 10px;
  }
  .el-dialog__header {
    padding: 20px !important;
  }
  .el-dialog__body {
    padding: 0 10px 10px 10px;
  }
}
</style>
